import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:permission_handler/permission_handler.dart';

class NotificationHelper {
  // 单例模式
  static final NotificationHelper _instance = NotificationHelper._internal();
  factory NotificationHelper() => _instance;
  NotificationHelper._internal();

  final FlutterLocalNotificationsPlugin _notificationsPlugin =
  FlutterLocalNotificationsPlugin();

  // 通知通道ID，确保唯一
  static const String _channelId = 'default_channel';
  static const String _channelName = '默认通知';
  static const String _channelDescription = '应用的默认通知通道';

  // 初始化函数
  Future<void> initialize() async {
    // 请求通知权限
    await _requestNotificationPermission();

    // 安卓初始化设置
    const AndroidInitializationSettings initializationSettingsAndroid =
    AndroidInitializationSettings('@mipmap/ic_launcher');

    // iOS初始化设置
    const DarwinInitializationSettings initializationSettingsIOS =
    DarwinInitializationSettings(
      requestAlertPermission: true,
      requestBadgePermission: true,
      requestSoundPermission: true,
    );

    // 初始化设置
    const InitializationSettings initializationSettings =
    InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS,
    );

    // 创建通知通道（针对Android O及以上）
    await _createNotificationChannel();

    await _notificationsPlugin.initialize(
      initializationSettings,
      // 可选：处理通知点击事件
      onDidReceiveNotificationResponse: (details) {
        // 处理通知点击
        debugPrint('通知被点击: ${details.payload}');
      },
    );
  }

  // 请求通知权限
  Future<void> _requestNotificationPermission() async {
    if (await Permission.notification.isDenied) {
      await Permission.notification.request();
    }
  }

  // 创建通知通道（Android O及以上必需）
  Future<void> _createNotificationChannel() async {
    const AndroidNotificationChannel channel = AndroidNotificationChannel(
      _channelId,
      _channelName,
      description: _channelDescription,
      importance: Importance.max,
      sound: RawResourceAndroidNotificationSound('notification'), // 可选：自定义通知声音
      playSound: true,
      enableVibration: true,
    );

    await _notificationsPlugin
        .resolvePlatformSpecificImplementation<
        AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);
  }

  // 显示通知
  Future<void> showNotification({
    required String title,
    required String body,
    int id = 0, // 允许不同ID的通知
    String? payload, // 可选：传递数据
  }) async {
    // 检查权限
    if (await Permission.notification.isGranted) {
      // 安卓通知详情
      const AndroidNotificationDetails androidNotificationDetails =
      AndroidNotificationDetails(
        _channelId,
        _channelName,
        channelDescription: _channelDescription,
        importance: Importance.max,
        priority: Priority.high,
        ticker: 'ticker',
        playSound: true,
        enableVibration: true,
        // 确保通知在锁屏上可见
        visibility: NotificationVisibility.public,
        // 通知样式
        styleInformation: BigTextStyleInformation(''),
      );

      // iOS通知详情
      const DarwinNotificationDetails iosNotificationDetails =
      DarwinNotificationDetails(
        presentAlert: true,
        presentBadge: true,
        presentSound: true,
      );

      // 跨平台通知设置
      const NotificationDetails platformChannelSpecifics =
      NotificationDetails(
        android: androidNotificationDetails,
        iOS: iosNotificationDetails,
      );

      // 显示通知
      await _notificationsPlugin.show(
        id,
        title,
        body,
        platformChannelSpecifics,
        payload: payload,
      );
    } else {
      debugPrint('没有通知权限，无法显示通知');
      // 可以在这里再次请求权限
      await _requestNotificationPermission();
    }
  }
}
